<template>
  <!-- 电吹风-个人统计 -->
  <div class="swipe_details">
    <el-form :inline="true" :model="elform" size="mini">
      <el-form-item label="部门:" >
        <el-select
          v-model="departmentGuid"
          placeholder="请选择"
          size="mini"
          clearable
          @change="selectdepartment"
          multiple
        >
          <el-option
            v-for="item in departmentoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名:">
        <el-input
          v-model="userName"
          placeholder="姓名"
          size="mini"
          clearable
          style="width: 120px"
        ></el-input>
      </el-form-item>
      <el-form-item label="卡号:">
        <el-input
          v-model="cardNumber"
          placeholder="卡号"
          size="mini"
          clearable
          style="width: 120px"
        ></el-input>
      </el-form-item>
      <el-form-item label="编号:">
        <el-input
          v-model="userNumber"
          placeholder="编号"
          size="mini"
          clearable
          style="width: 120px"
        ></el-input>
      </el-form-item>

      <el-form-item label="" label-width="40px">
        <el-checkbox v-model="includeNoSuccess">是否包含非确定交易</el-checkbox>
      </el-form-item>
      <!-- <el-form-item label="分组:" >
        <el-select
          v-model="groupingGuid"
          placeholder="请选择"
          size="mini"
          clearable
          @change="selectdepartment"
          multiple
        >
          <el-option
            v-for="item in groupingoption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item> -->
         <el-form-item label="开始日期:">
        <el-date-picker
          v-model="datetime[0]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[0]"
          value-format="HH:mm:ss"
          placeholder="开始时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item label="结束日期:">
        <el-date-picker
          v-model="datetime[1]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[1]"
          value-format="HH:mm:ss"
          placeholder="结束时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item class="searchmarigin">
        <el-button
          type="primary"
          @click="onSubmit"
          size="mini"
          icon="el-icon-search"
          >查询</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onExport"
          size="mini"
          icon="el-icon-document-copy"
          >导出</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onExport('print')"
          size="mini"
          icon="el-icon-printer"
          >打印</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-popover width="600" placement="top" trigger="click">
          <el-row>
            <el-col
              :span="6"
              v-for="item in Object.keys(formThead)"
              :key="item"
            >
              <el-checkbox
                :label="formThead[item].label"
                v-model="formThead[item].checked"
                @change="getHeaderDate()"
              ></el-checkbox>
            </el-col>
          </el-row>
          <el-button
            slot="reference"
            size="mini"
            type="primary"
            icon="el-icon-edit-outline"
            >自定义</el-button
          >
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tablemain">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        style="width: 100%"
        :header-cell-style="headFirst"
        :cell-style="
          detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
        "
      >
        <!-- <el-table-column
               type="index"
              >
        </el-table-column>-->
        <el-table-column
          prop="userName"
          label="姓名"
          v-if="formThead.userName.checked"
        ></el-table-column>
        <el-table-column
          prop="departmentName"
          label="部门"
          v-if="formThead.departmentName.checked"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          prop="cardNumber"
          label="卡号"
          min-width="120px"
          v-if="formThead.cardNumber.checked"
        >
        </el-table-column>
        <el-table-column
          prop="userNumber"
          label="人员编号"
          min-width="120px"
          v-if="formThead.userNumber.checked"
        >
        </el-table-column>
        <el-table-column
          prop="minExpenditure"
          label="最小消费金额(元)"
          v-if="formThead.minExpenditure.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.minExpenditure | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="maxExpenditure"
          label="最大消费金额(元)"
          v-if="formThead.maxExpenditure.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.maxExpenditure | amountyuan }}</div>
          </template>
        </el-table-column>

        <el-table-column
          prop="avgExpenditure"
          label="平均消费金额(元)"
          v-if="formThead.avgExpenditure.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.avgExpenditure | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="count"
          label="消费次数"
          v-if="formThead.count.checked"
          min-width="120px"
        ></el-table-column>
        <el-table-column
          prop="sumExpenditure"
          label="合计消费金额(元)"
          v-if="formThead.sumExpenditure.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.sumExpenditure | amountyuan }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column
               prop="sumExpenditure"
               label="钱包类型"
            >
        </el-table-column>-->
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangepage"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      filename: "电吹风个人统计报表",
      departmentoptions: [],
      departmentGuid: [],
      groupingoption: [],
      groupingGuid: [],
      userName: "",
      cardNumber: "",
      userNumber: "",
      datetime: [],
      time:[],
      dataType: [],
      elform: {},
      // 是否包含非确定交易
      includeNoSuccess: false,
      //
      detailslist: [],
      loading: false,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead: {
        userName: { label: "姓名", prop: "userName", checked: true },
        departmentName: {
          label: "部门",
          prop: "departmentName",
          checked: true,
        },
        cardNumber: { label: "卡号", prop: "cardNumber", checked: true },
        userNumber: {
          label: "人员编号",
          prop: "userNumber",
          checked: false,
        },
        minExpenditure: {
          label: "最小消费金额(元)",
          prop: "minExpenditure",
          checked: true,
        },
        maxExpenditure: {
          label: "最大消费金额(元)",
          prop: "maxExpenditure",
          checked: true,
        },
        avgExpenditure: {
          label: "平均消费金额(元)",
          prop: "avgExpenditure",
          checked: true,
        },
        count: {
          label: "消费次数",
          prop: "count",
          checked: true,
        },
        sumExpenditure: {
          label: "合计消费金额(元)",
          prop: "sumExpenditure",
          checked: true,
        },
      },
      //导出数据
      detailslistExportlist: [],
      //汇总合计
      detailsTotal: null,
    };
  },
  created() {
    this.datetime = [this.getNowTime('yy-mm-dd'), this.getNowTime('yy-mm-dd')]
    this.time = ['00:00:00', '23:59:59']
  },
  mounted() {
    this.departmentselectlist();
    this.unitgroup();
  },
  filters: {},
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid;
      },
    },
  },
  methods: {
    // 重新渲染表格
    getHeaderDate() {
      this.$nextTick(() => {
        this.$refs["table"].doLayout();
      });
    },
    //合计查询
    searchtotal() {
      this.searchInfo.unitGuid = this.changeschoolid;
      this.detailsTotal = null;
      let _this = this;
      _this.loading = true;
      return new Promise(function (resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              "/terminal/hair/hair-drier-statistics-total"
            ),
            method: "post",
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0,
            }),
          })
          .then(({ data }) => {
            _this.loading = false;
            if (data.messageCode == 200) {
              if (data.messageContent) {
                _this.detailsTotal = {
                  ...data.messageContent,
                  //   departmentName: "合计：",

                  //最小消费金额
                  minExpenditure: "",

                  //最大消费金额
                  maxExpenditure: "",

                  //平均消费金额
                  avgExpenditure: "",
                };
              }
              resolve(data.messageContent);
            } else {
              _this.$message.error(data.errorMessage);
              reject(data.errorMessage);
            }
          });
      });
    },
    //部门选择
    departmentselectlist() {
      this.departmentoptions = [];
      this.$http({
        url: this.$http.adornUrl("/department/query-department-info"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent;
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName,
            };
            this.departmentoptions.push(itemobj);
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    //单位分组查询
    unitgroup() {
      this.groupingoption = [];
      this.$http({
        url: this.$http.adornUrl("/unit/unit-user-group-list"),
        method: "post",
        data: this.$http.adornData({
          messageContent: this.changeschoolid,
          messageType: 0,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent;
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].groupGuid,
              label: Arr[i].groupName,
            };
            this.groupingoption.push(itemobj);
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    selectdepartment() {},
    // 查询
    async onSubmit() {
      this.pageNum = 1;
      this.searchInfo = {};
      this.searchInfo.unitGuid = this.changeschoolid;
      this.searchInfo.includeNoSuccess = this.includeNoSuccess;
      if (this.departmentGuid != "") {
        this.searchInfo.departmentGuidList = this.departmentGuid;
      }
      if (this.userName != "") {
        this.searchInfo.userName = this.userName;
      }
      if (this.cardNumber != "") {
        this.searchInfo.cardNumber = this.cardNumber;
      }
      if (this.userNumber != "") {
        this.searchInfo.userNumber = this.userNumber;
      }
      //   if (this.groupingGuid != "") {
      //     this.searchInfo.groupGuidList = this.groupingGuid;
      //   }
      if (this.datetime != null && this.datetime != "") {
        this.searchInfo.startTime = this.datetime[0] + ' ' + this.time[0]
        this.searchInfo.endTime = this.datetime[1] + ' ' + this.time[1]
      }
      if (this.dataType !== null && this.dataType !== "") {
        this.searchInfo.chargingTypeList = this.dataType;
      }
      await this.searchtotal();
      this.detailspage();
    },
    //刷卡明细分页查询
    detailspage() {
      this.loading = true;
      this.searchInfo.unitGuid = this.changeschoolid;
      this.$http({
        url: this.$http.adornUrl("/terminal/hair/hair-drier-statistics-page"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        this.loading = false;
        if (
          data.messageContent.data == null ||
          data.messageContent.data.length == 0
        ) {
          this.$message({
            message: "查询成功当前暂无数据",
            type: "success",
          });
        }
        if (data.messageCode == 200) {
          this.detailslist = data.messageContent.data || [];
          this.recordCount = data.messageContent.recordCount;
          this.currentPage = data.messageContent.pageNum;
          if (this.detailslist != 0) {
            this.detailslist.push({...this.detailsTotal});
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    async onExport(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: "请查询数据后,在进行此操作",
          type: "warning",
        });
        return false;
      }
      await this.outexecelinit();
      if (type == "print") {
        this.printJS();
      } else {
        this.export2Excel();
      }
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist;
      const title = "电吹风个人统计表";
      this.unitName = sessionStorage.getItem("unitName");
      const properties = [];
      // 拿到数据formThead
      for (let key in this.formThead) {
        if (this.formThead[key].checked) {
          properties.push({
            displayName: this.formThead[key].label,
            field: this.formThead[key].prop,
          });
        }
      }
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            "yyyy-MM-dd"
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            "yyyy-MM-dd"
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: "json",
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem("username"),
          this.getNowTime("yy-mm-dd hh:mm:ss")
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle(),
      });
    },
    //刷卡明细导出数据
    outexecelinit() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              "/terminal/hair/hair-drier-statistics-page"
            ),
            method: "post",
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo,
              },
              messageType: 0,
            }),
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.detailslistExportlist = data.messageContent.data;
              _this.detailslistExportlist.push({ ..._this.detailsTotal });
              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[i].sumExpenditure = _this.amountyua(
                  _this.detailslistExportlist[i].sumExpenditure
                );
                _this.detailslistExportlist[i].minExpenditure = _this.amountyua(
                  _this.detailslistExportlist[i].minExpenditure
                );
                _this.detailslistExportlist[i].maxExpenditure = _this.amountyua(
                  _this.detailslistExportlist[i].maxExpenditure
                );

                _this.detailslistExportlist[i].avgExpenditure = _this.amountyua(
                  _this.detailslistExportlist[i].avgExpenditure
                );
              }
              resolve(_this.detailslistExportlist);
            } else {
              reject(data.errorMessage);
              _this.$message.error(data.errorMessage);
            }
          });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    export2Excel() {
      const nowtime = this.getimeto();
      require.ensure([], () => {
        const multiHeader = [];
        const multiHeader2 = [];
        const merges = [];
        const { export_json_to_excel } = require("../../excel/Export2Excel");
        // tHeaderarr.push('部门名称')

        let tHeader = [];
        let filterVal = [];
        for (let key in this.formThead) {
          if (this.formThead[key].checked) {
            tHeader.push(this.formThead[key].label);
            filterVal.push(this.formThead[key].prop);
          }
        }

        const list = this.detailslistExportlist;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime,
        });
      });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.detailspage();
    },
    handleCurrentChangepage(val) {
      this.pageNum = val;
      this.detailspage();
    },
  },
};
</script>

<style lang="scss" scoped>
.swipe_details {
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  .el-form-item {
    margin-bottom: 5px;
  }
  .demo-form-inline,
  .demo-form-inline1 {
    /deep/.el-form-item__label {
      padding-right: 5px;
    }
    .el-form-item {
      margin-bottom: 5px;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 350px;
    }
  }
  .demo-form-inline1 {
    border-bottom: 1px solid #e5e9f2;
    .searchmarigin {
      margin-left: 20px;
    }
  }
  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>